package com.zzyl.nursing.service.member.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.filter.UserThreadLocal;
import com.zzyl.nursing.domain.member.Reservation;
import com.zzyl.nursing.mapper.member.ReservationMapper;
import com.zzyl.nursing.service.member.IReservationService;
import com.zzyl.nursing.vo.member.CountByTimeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 预约信息Service业务层处理
 * 
 * @author zzyl_mh
 * @date 2025-08-18
 */
@Service
@Slf4j
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService
{
    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 查询预约信息
     * 
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id)
    {
        return reservationMapper.selectById(id);
    }

    /**
     * 查询预约信息列表
     * 
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation)
    {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息
     * 
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation)
    {
        Long userId = UserThreadLocal.getUserId();
        reservation.setCreateBy(userId);
        reservation.setUpdateBy(userId);
        //先查询该用户是否在同一时间点多次预约
        LambdaQueryWrapper<Reservation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Reservation::getTime, reservation.getTime())
                .eq(Reservation::getCreateBy, userId)
                .eq(Reservation::getStatus, 0);
        if (count(wrapper) > 0) {
            throw new RuntimeException("您已经预约该时间段,不可以重复预约");
        }
        reservation.setUpdateTime(LocalDateTime.now());
        reservation.setCreateTime(LocalDateTime.now());
        reservation.setStatus(0);
        return reservationMapper.insert(reservation);
    }

    /**
     * 修改预约信息
     * 
     * @param id 预约信息
     * @return 结果
     */
    @Override
    public void updateReservation(Long id)
    {
        //将状态设为 2
        Reservation reservation = getById(id);
        reservation.setUpdateBy(UserThreadLocal.getUserId());
        reservation.setUpdateTime(LocalDateTime.now());
        reservation.setStatus(2);
        updateById(reservation);
    }


    /**
     * 查询当天取消预约数量
     */
    @Override
    public long cancelledCount() {
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        Long userId = UserThreadLocal.getUserId();
        log.info("查询参数: userId={}, startTime={}, endTime={}", userId, startTime, endTime);
        LambdaQueryWrapper<Reservation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Reservation::getStatus, 2)
                .eq(Reservation::getUpdateBy, userId)
                .between(Reservation::getCreateTime, startTime, endTime);
        Long count = reservationMapper.selectCount(wrapper);
        log.info("查询结果: count={}", count);
        return count;
    }

    /**
     * 查询每个时间段剩余预约次数
     * @param time
     * @return
     */
    @Override
    public List<CountByTimeVo> countByTime(long time) {
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        // 调用持久层方法
        List<CountByTimeVo> list = reservationMapper.countByTime(startTime, endTime);
        return list;
    }

    /**
     * 修改预约状态(定时任务)
     */
    @Override
    public void updateReservationStatus() {
        LocalDateTime now = LocalDateTime.now();
        //待报到 --> 过期
        List<Reservation> list = this.lambdaQuery()
                .eq(Reservation::getStatus, 0)
                .le(Reservation::getTime, now)
                .list();
        if(CollUtil.isNotEmpty(list)){
            list.forEach(reservation -> reservation.setStatus(3));
            this.updateBatchById(list);
        }

    }
}
